package com.pjj.userservice.utils;

import com.pjj.userservice.pojo.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;

public class TokenUtil {
    private static final String SECRET = "pjj-mua";
    private static final Long EXPIRATION = 604800L;

    public static String generateToken(User user) {
        Date now = new Date();
        Date expiration = new Date(now.getTime() + EXPIRATION * 1000);

        return Jwts.builder()
                .setId(user.getId())
                .setSubject(user.getPassword())
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .setExpiration(expiration)
                .compact();
    }

    public static Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            System.out.println("Error while parsing JWT claims: " + e.getMessage());
        }
        return claims;
    }
}
